package com.zhdl.network.pcb.after;

import cn.hutool.core.util.HexUtil;
import com.project.command.instruction.strategy.abs.AbsAfterControlCommand;
import com.project.command.instruction.strategy.process.data.AfterStrategyParam;
import com.project.common.util.ByteHelper;
import com.zhdl.common.eventbus.center.EventBusCenter;
import com.zhdl.network.modbus.dto.ModbusDto;
import com.zhdl.network.pcb.dto.PcbDto;
import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service(PcbAfterService.PCB_AFTER_SERVICE)
public class PcbAfterService extends AbsAfterControlCommand<PcbDto, ByteBuf> {
    public static final String PCB_AFTER_SERVICE = "pcbAfterService";

    /**
     * 后置处理结果判断
     *
     * @param resp
     * @return
     */
    @Override
    public boolean afterResultJudge(AfterStrategyParam resp) {
        log.debug("执行PCB_AFTER_SERVICE pcbAfterService");

        List<byte[]> bytes = resp.getNewData();
        byte[] bytes1 = bytes.get(0);
        String s = HexUtil.encodeHexStr(bytes1);
        System.out.println(s);
        ModbusDto modbusDto = new ModbusDto();
        String substring = s.substring(14);
//        String type = substring.substring(0,2);
        String instruction = resp.getInstruction().replaceAll(" ", "");
        String type = instruction.substring(14, 16);
        modbusDto.setCmdType((byte) Integer.parseInt(type, 16));

        switch (type) {
            case "06", "05", "10", "0F" -> {
                modbusDto.setFullBuff(bytes1);
                modbusDto.setUnitBuff(ByteHelper.hexString2Bytes(substring));
            }
            case "01", "03", "02" -> {
                modbusDto.setFullBuff(bytes1);
                modbusDto.setUnitBuff(ByteHelper.hexString2Bytes(substring.substring(4)));
            }
            default -> {
                System.out.println("功能码为：" + type + "，未匹配到对应的功能码");
            }
        }
        List<ModbusDto> temp = new ArrayList<>();
        temp.add(modbusDto);
        resp.setNewData(temp);
        EventBusCenter.getEventBus().post(resp);
        log.info("COM" + resp.getPortKey() + "发送指令>>>>" + resp.getInstruction() + "<<<<<<<收到指令" + HexUtil.encodeHexStr(modbusDto.getFullBuff()));
        return true;
//        log.debug("执行MOTOR_AFTER_SERVICE modbusAfterService");
//        List<PcbDto> list = resp.getNewData();
//        //此处接收串口或网口客户端回应代码,并处理
//        PcbDto pcbDto = list.get(0);
//        String instruction = resp.getInstruction();
//        EventBusCenter.getEventBus().post(resp);
//        //cmdHandleService.getStatus(resp);
//        log.info(Thread.currentThread().getName() + "------------------");
//        log.info("COM" + resp.getPortKey() + "发送指令>>>>" + instruction + "<<<<<<<收到指令" + HexUtil.encodeHexStr(pcbDto.getFullBuff()));
//        return true;
    }
}
